var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var Base = require('../base.js');
var app = getApp();

var CateList = function({
  page,
  scope,
  cmpt
}) {
  Base.apply(this, arguments);
  this.init();
}

common.extend(CateList, Base);

Object.assign(CateList.prototype, {
  init() {
    this.setData({
      isCatHide: true,

      curTy: 0,
      curTyName: '',
      catList: [],
      goodsList: [],

      page: 1,
      loading: false,
      moreLoading: false,
      noMore: false,

      winHei: app.getWinHei()

    });

    this._getList();
  },

  _switchCat(evt) {
    var catId = evt.target.dataset.catId;
    var formId = evt.detail.formId;
    var catList = this.getData('catList') || [];
    var subCates;

    catList.some((cate) => {
      if (cate.category_id == catId) {
        subCates = cate.sub_category_list || [];
        return true;
      }
    });

    this.setData({
      curTy: catId,
      subCates,
      curSubTy: 0,
      page: 1,
      isCatHide: true,
    });

    this._getList();
    common.submitForm(formId);
  },

  _switchSubCat(evt) {
    var catId = evt.target.dataset.catId;

    this.setData({
      curSubTy: catId,
      page: 1,
    });

    this._getList();
  },

  _getList(options) {
    var _self = this;
    var {
      isMore,
    } = options || {};
    var page = (options && options.page) || _self.getData('page') || 1;
    var curSubTy = _self.getData('curSubTy');
    var curTy = _self.getData('curTy');
    var ajaxParams,
      ajaxUrl = '/openapi/CHome/categoryPage';

    if (isMore) {
      _self.setData({
        moreLoading: true
      });
    } else {
      _self.setData({
        loading: true
      });
    }

    ajaxUrl = '/openapi/CHome/categoryPage';
    ajaxParams = {
      catId: curSubTy && curSubTy != 0 ? curSubTy : curTy,
      page
    };

    ajax.G(ajaxUrl, ajaxParams, function(data) {
      var {
        catList = [], goodsList = [], parentCatId, catId, parentCatIdTitle,
      } = data.result;
      var allGoodsList = _self.getData('goodsList') || [];
      var oldCatList = _self.getData('catList');

      var toData = {
        goodsList: isMore ? allGoodsList.concat(goodsList) : goodsList,
        // catList,
        noMore: goodsList.length == 0,
        page: _self.getData('page') + 1,
        curTyName: parentCatIdTitle,
      };

      if (!oldCatList || oldCatList.length == 0) {
        toData.catList = catList;
        toData.curTy = parentCatId;
        toData.curSubTy = catId == parentCatId ? 0 : catId;
      }

      toData['serchTip'] = '';

      toData[isMore ? 'moreLoading' : 'loading'] = false;
      _self.setData(toData);
    });
  },

  /**
   * 加载更多
   */
  _loadMore: function() {
    if (this.getData('moreLoading') || this.getData('loading') || this.getData('noMore')) {
      return;
    }

    this._getList({
      isMore: true,
    });
  },


});

CateList.props = {
  name: 'cateList'
};

module.exports = CateList;